import React, {Component} from 'react';
import AssetItems from './AssetItems';
import fetch from '../helpers/fetcher';

import './App.css';

let session = localStorage.getItem('session');
try{
  session = JSON.parse(session);
} catch(e) {
  session = null;
}

const initState = {
  items: [],
  range: {
    start: 0,
    end: 10
  },
  noMore: false,
  session: session,
  showLoginForm: false,
  loginForm: {
    login: '',
    password: '',
    useLdap: true
  }
};

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = Object.assign({}, initState);

    this.refresh = this.refresh.bind(this);
    this.fetchAssets = this.fetchAssets.bind(this);
    this.toggleLogin = this.toggleLogin.bind(this);
    this.logout = this.logout.bind(this);
    this.login = this.login.bind(this);
    this.handleLoginFormFieldChange = this.handleLoginFormFieldChange.bind(this);
  }

  fetchAssets(next) {
    if (this.state.noMore) {
      console.log('noMore: ', this.state);
      return;
    }
    // 若取当前的开始与结速位置
    let {start, end, total} = this.state.range;
    let [skip,
      limit] = [
      start, end - start
    ];
    if (typeof total === 'number') {
      // 若请示的是下一页
      if (next) {
        skip += limit;
      }
    }

    let options = {
      query: {
        skip: skip,
        limit: limit
      }
    }
    fetch(`/asset/assets`, options).then(json => {
      let {items, noMore} = this.state;
      let {range} = json;
      noMore = range.end === range.total;

      json.items.forEach(item => items.push(item));

      this.setState({items, range, noMore});
    });
  }

  refresh() {
    this.setState({
      items: [],
      range: {
        start: initState.range.start,
        end: initState.range.end
      },
      noMore: false
    });
    console.log('refreshing', this.state);
    this.fetchAssets();
  }

  toggleLogin() {
    this.setState({
      showLoginForm: !this.state.showLoginForm
    });
  }

  login(e) {
    e.preventDefault();
    console.log(e.target);
    fetch('/sign/in', {
      body: this.state.loginForm,
      method: 'POST'
    }).then(session => {
      this.setState({
        session: session
      });

      localStorage.setItem('session', JSON.stringify(session));

      console.log(this.state.session);
    })
  }

  logout() {
    this.setState({
      session: null,
      showLoginForm: false
    });
  }

  handleLoginFormFieldChange(e) {
    let update = this.state.loginForm;
    update[e.target.name] = e.target.value;
    this.setState({
      loginForm: update
    });
    console.log(this.state.loginForm);
  }

  componentWillMount() {
    this.fetchAssets();
  }

  render() {
    return (
      <div className="app">
        <h1>资产列表
          <small>
            (总计: { this.state.range ? this.state.range.total : 0} )
          </small>
          <button onClick={this.refresh}>刷新</button>
        {
          this.state.session ?
          <span>
            { this.state.session.credentials.displayName }您好 |
            <button onClick={this.logout}>退出登录</button>
          </span>
          :
          <button onClick={this.toggleLogin}>{
            this.state.showLoginForm ? '取消' : '登录'
          }</button>
        }
        </h1>

        {
          this.state.showLoginForm & !this.state.session ?
          <form onSubmit={this.login}>
            <input onChange={this.handleLoginFormFieldChange} name='login' type='text' placeholder='输入用户名'/> <br />
            <input onChange={this.handleLoginFormFieldChange} name='password' type='password' placeholder='输入用户密码' /> <br />
            <button type='submit'>登录</button>
          </form> :
          null
        }

        <AssetItems entities={this.state.items}/>
        { this.state.noMore ? '已经见底了' : <button onClick={ () => { this.fetchAssets(true) }}>加载更多</button>}
      </div>
    );
  }
};
